package qmsz.api.utils;

import java.security.SecureRandom;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;

public final class QMSZUtils {
	private QMSZUtils() {}
	
	private static final Logger logger = Logger.getLogger(QMSZUtils.class);
	
	public static void tryClose(AutoCloseable... objects) {
		for (AutoCloseable object : objects) {
			if (object != null) {
				try {
					object.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static JSONObject simpleResponse(ResponseCode code) {
		JSONObject value = new JSONObject();
		value.put("code", code.getCode());
		value.put("msg", code.getMsg());
		return value;
	}
	
	public static JSONObject simpleResponse(ResponseCode code, String msg) {
		JSONObject value = new JSONObject();
		value.put("code", code.getCode());
		value.put("msg", msg);
		return value;
	}
	
	public static JSONObject queryResponse(Object result) {
		if (result == null) {
			return QMSZUtils.simpleResponse(ResponseCode.FAIL_SQL_SEARCH);
		} else {
			JSONObject value = QMSZUtils.simpleResponse(ResponseCode.SUCCESS);
			value.put("result", result);
			return value;
		}
	}
	
	public static JSONObject queryResponse(List<?> results) {
		if (results == null || results.size() <= 0) {
			return QMSZUtils.simpleResponse(ResponseCode.FAIL_SQL_SEARCH);
		} else {
			JSONObject value = QMSZUtils.simpleResponse(ResponseCode.SUCCESS);
			value.put("results", results);
			return value;
		}
	}
	
	public static boolean checkRequestSign(JSONObject request, String... signKeys) {
		String sign = request.getString("sign");
		if (sign == null)
			return false;
		StringBuilder rawSign = new StringBuilder();
		for (String signKey : signKeys) {
			Object signValue = request.get(signKey);
			if (signValue == null)
				return false;
			rawSign.append(signValue);
		}
		return sign.equals(DigestUtils.md5Hex(rawSign.toString()));
	}
	
	public static void insertTimestamp(JSONObject requestParams) {
		requestParams.put("timestamp", String.valueOf(new Date().getTime() / 1000));
	}
	
	public static void WYZSSignGenerator(JSONObject requestParams, String appsec) {
		TreeMap<String, Object> tm = new TreeMap<String, Object>();
		requestParams.forEach((s, o) -> tm.put(s, o));
		StringBuilder sb = new StringBuilder();
		tm.forEach((s, o) -> {
			sb.append('&');
			sb.append(s);
			sb.append('=');
			sb.append(o);
		});
		sb.append("&authcode=" + appsec);
		requestParams.put("sign", DigestUtils.md5Hex(sb.toString().toLowerCase()));
	}
	
	public static String WYSZEncryptCardPwd(String content, String key) {
		String value = null;
		try {
        	SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key.getBytes());
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] byteRresult = cipher.doFinal(byteContent);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < byteRresult.length; i++) {
                String hex = Integer.toHexString(byteRresult[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            value = sb.toString();
        } catch (Exception e) {
        	logger.error("utils error", e);
        	value = null;
        }
        return value;
    }
	
	public static String WYSZDecryptCardPwd(String content, String key) {
		if (content.length() < 1) { return null; }
		String value = null;
        byte[] byteRresult = new byte[content.length() / 2];
        for (int i = 0; i < content.length() / 2; i++) {
            int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
            byteRresult[i] = (byte) (high * 16 + low);
        }
        try {
        	SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(key.getBytes());
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] result = cipher.doFinal(byteRresult);
            value = new String(result);
        } catch (Exception e) {
        	logger.error("utils error", e);
        	value = null;
        }
        return value;
	}
}
